<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" inline v-show="showSearch" label-width="68px">
      <el-form-item label="标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入标题"
          clearable
          size="small"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="发布时间" prop="publishDatetime">
        <el-date-picker
          v-model="queryParams.publishDatetime"
          type="datetime"
          value-format="yyyy-MM-dd HH:mm:ss"
          placeholder="选择发布时间"
          clearable
          size="small"
        />
      </el-form-item>
      <el-form-item label="发布者" prop="publisher">
        <el-input
          v-model="queryParams.publisher"
          placeholder="请输入发布者"
          clearable
          size="small"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['bid:policylaw:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['bid:policylaw:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['bid:policylaw:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['bid:policylaw:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="policylawList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="主键" align="center" prop="id" /> -->
      <el-table-column label="No." type="index" width="50" />
      <el-table-column label="标题" align="center" prop="title" />
      <el-table-column label="发布时间" align="center" prop="publishDatetime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.publishDatetime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="发布者" align="center" prop="publisher" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['bid:policylaw:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['bid:policylaw:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改政策法规对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="发布时间" prop="publishDatetime">
          <el-date-picker
            v-model="form.publishDatetime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择发布时间"
            clearable
            size="small"
          />
        </el-form-item>
        <el-form-item label="发布者" prop="publisher">
          <el-input v-model="form.publisher" placeholder="请输入发布者" />
        </el-form-item>
        <el-form-item label="内容">
          <editor v-model="form.content" :min-height="192" :height="400" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="上传文件">
          <file-upload
            v-model="fileList"
            :file-type="fileType"
            :file-size="100"
            :limit="10"
            v-if="showFileList"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import {
  listPolicylaw,
  getPolicylaw,
  delPolicylaw,
  addPolicylaw,
  updatePolicylaw,
  exportPolicylaw
} from '@/api/bid/policylaw';
import Editor from '@/components/MyEditor/index';
import ImageUpload from '@/components/ImageUpload';
import FileUpload from '@/components/FileUpload';

// 响应式状态
const loading = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const showSearch = ref(true);
const total = ref(0);
const policylawList = ref([]);
const title = ref("");
const open = ref(false);

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  title: null,
  content: null,
  publishDatetime: null,
  publisher: null,
});

// 表单数据
const form = reactive({
  id: null,
  title: null,
  content: null,
  publishDatetime: null,
  publisher: null,
  createBy: null,
  createTime: null,
  updateBy: null,
  updateTime: null,
  remark: null,
});

// 表单校验规则
const rules = {
  title: [{ required: true, message: "标题不能为空", trigger: "blur" }],
  content: [{ required: true, message: "内容不能为空", trigger: "blur" }],
};

const fileList = ref([]);
const fileType = ref(['pdf', 'zip', 'rar', 'png', 'jpg', 'jpeg']);
const showFileList = ref(false);

// 获取表单组件引用
const queryForm = ref(null);
const formRef = ref(null);

// 工具函数：parseTime（根据需求自行实现，此处为简单返回）
function parseTime(time, format) {
  return time;
}

// 获取列表数据
const getList = async () => {
  loading.value = true;
  try {
    const response = await listPolicylaw(queryParams);
    policylawList.value = response.rows;
    total.value = response.total;
  } finally {
    loading.value = false;
  }
};

// 取消按钮
const cancel = () => {
  open.value = false;
  reset();
};

// 表单重置
const reset = () => {
  Object.assign(form, {
    id: null,
    title: null,
    content: null,
    publishDatetime: null,
    publisher: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    remark: null,
  });
  formRef.value?.resetFields();
  nextTick(() => {
    fileList.value = [];
    showFileList.value = false;
    // 切换以触发重新渲染
    showFileList.value = true;
  });
};

// 搜索操作
const handleQuery = () => {
  queryParams.pageNum = 1;
  getList();
};

// 重置搜索
const resetQuery = () => {
  queryForm.value?.resetFields();
  handleQuery();
};

// 多选框选中数据
const handleSelectionChange = (selection) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length !== 1;
  multiple.value = selection.length === 0;
};

// 新增操作
const handleAdd = () => {
  reset();
  open.value = true;
  title.value = "添加政策法规";
};

// 修改操作
const handleUpdate = async (row) => {
  reset();
  const id = row?.id || ids.value;
  try {
    const response = await getPolicylaw(id);
    Object.assign(form, response.data);
    if (response.data.filesList) {
      fileList.value = response.data.filesList.map(x => ({
        fileName: x.fileName,
        originalFileName: x.fileName,
        url: x.filePath,
      }));
    }
    open.value = true;
    title.value = "修改政策法规";
  } catch (error) {
    console.error(error);
  }
};

// 提交表单
const submitForm = () => {
  if (fileList.value) {
    const file = [];
    fileList.value.forEach(item => {
      file.push({
        fileName: item.originalFileName,
        filePath: item.url,
      });
    });
    form.filesList = file;
  }
  formRef.value?.validate(async (valid) => {
    if (valid) {
      try {
        if (form.id != null) {
          await updatePolicylaw(form);
          ElMessage.success("修改成功");
        } else {
          await addPolicylaw(form);
          ElMessage.success("新增成功");
        }
        open.value = false;
        getList();
      } catch (error) {
        console.error(error);
      }
    }
  });
};

// 删除操作
const handleDelete = async (row) => {
  const deleteIds = row?.id || ids.value;
  try {
    await ElMessageBox.confirm(
      `是否确认删除政策法规编号为"${deleteIds}"的数据项?`,
      "警告",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }
    );
    await delPolicylaw(deleteIds);
    ElMessage.success("删除成功");
    getList();
  } catch (error) {
    console.error(error);
  }
};

// 导出操作
const handleExport = async () => {
  try {
    await ElMessageBox.confirm(
      '是否确认导出所有政策法规数据项?',
      "警告",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }
    );
    const response = await exportPolicylaw(queryParams);
    // download 为你自定义的下载方法，请根据项目实际情况实现
    download(response.msg);
  } catch (error) {
    console.error(error);
  }
};

onMounted(() => {
  getList();
});
</script>
